package com.caifu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.caifu.bean.Result;
import com.caifu.bean.ResultUtil;
import com.caifu.mapper.*;
import com.caifu.pojo.*;
import com.caifu.service.COrgService;
import com.caifu.util.ShiroUtil;
import com.caifu.util.Util;
import com.caifu.util.Utils;
import com.caifu.vo.CorgVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 * 机构用户表 服务实现类
 * </p>
 *
 * @author tww
 * @since 2020-12-10
 */
@Service
@Transactional(rollbackFor = RuntimeException.class)
public class COrgServiceImpl extends ServiceImpl<COrgMapper, COrg> implements COrgService {

    @Resource
    private COrgMapper orgMapper;

    @Resource
    private CDOrgMapper cdOrgMapper;

    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private SysUserMenuMapper sysUserMenuMapper;

    @Resource
    private SysMenuMapper sysMenuMapper;

    @Override
    public List<COrg> listOrg() throws Exception {
        try {
            return orgMapper.listOrg();
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception();
        }
    }


    @Override
    public Result addOrUpdate(COrg cOrg, SysUser user) {
        //盐
        String salt = Util.getStringRandom(20);
        //id不为空修改
        if (Utils.isNull(cOrg.getId())) {

            //校验账号是否存在
            if (checkUserIdIsExist(cOrg.getUserId())) {
                return ResultUtil.success(9999, "账号已存在");
            }

            cOrg.setCreateTime(new Date());
            cOrg.setStatus("1");
            orgMapper.insert(cOrg);
            SysUser sysUser = new SysUser();
            sysUser.setUserId(cOrg.getUserId());
            sysUser.setUserPwd(ShiroUtil.sha256("123456", salt));
            sysUser.setUserType("1");
            sysUser.setRelativeId(cOrg.getId());
            sysUser.setCreateBy(String.valueOf(user.getId()));
            sysUser.setSalt(salt);
            sysUser.setPaw("123456");
            sysUser.setStatus("1");
            sysUser.setToken("");
            sysUser.setLoginTime(new Date());
            sysUserMapper.insert(sysUser);

            //添加机构菜单
            SysUserMenu sysUserMenu = new SysUserMenu();
            sysUserMenu.setUserNo(sysUser.getId());
            //查询机构菜单
            QueryWrapper<SysMenu> queryWrapper = new QueryWrapper<>();
            queryWrapper.like("user_type", "1");
            List<SysMenu> sysMenus = sysMenuMapper.selectList(queryWrapper);
            for (SysMenu sysMenu : sysMenus) {
                sysUserMenu.setMenuNo(sysMenu.getMenuNo());
                sysUserMenuMapper.insert(sysUserMenu);
            }
        } else {
            COrg org = orgMapper.selectById(cOrg.getId());
            if (Utils.isNotNull(org)) {
                org.setOrgName(cOrg.getOrgName());
                org.setStartTime(cOrg.getStartTime());
                org.setOverdueTime(cOrg.getOverdueTime());
            }
            SysUser sysUser = sysUserMapper.selectOne(new QueryWrapper<SysUser>()
                    .eq("relative_id", cOrg.getId())
                    .eq("status", "1")
                    .eq("user_type", 1));
            if (!sysUser.getUserId().equals(cOrg.getUserId())) {
                //校验账号是否存在
                if (checkUserIdIsExist(cOrg.getUserId())) {
                    return ResultUtil.success(9999, "账号已存在");
                }
                sysUser.setUserId(cOrg.getUserId());
                sysUserMapper.updateById(sysUser);
            }
            orgMapper.updateById(org);
        }
        return ResultUtil.success(200, "保存成功");
    }

    @Override
    public PageInfo<CorgVo> getOrgList(CorgVo corgVo) {
        Map<String, Object> params = new HashMap<>();
        if (Utils.isNotNull(corgVo)) {
            params.put("orgName", corgVo.getOrgName());
            params.put("status", corgVo.getStatus());
        }
        PageHelper.startPage(corgVo.getCurrentPage(), corgVo.getPageSize());
        List<CorgVo> corgVos = orgMapper.getOrgList(params);
        //启用
        String flag = "1";
        for (CorgVo vo : corgVos) {
            if (flag.equals(vo.getStatus())) {
                vo.setFuck("启用");
            } else {
                vo.setFuck("停用");
            }
        }
        PageInfo<CorgVo> pageInfo = new PageInfo<>(corgVos);
        return pageInfo;
    }

    @Override
    public COrg getOrgById(String id) {
        return orgMapper.selectById(id);
    }

    @Override
    public Result resetPwd(Integer id) {
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("relative_id", id).eq("status", 1).eq("user_type", 1);
        SysUser user = sysUserMapper.selectOne(queryWrapper);
        if (Utils.isNotNull(user)) {
            //重置密码
            user.setUserPwd(ShiroUtil.sha256("123456", user.getSalt()));
        }
        sysUserMapper.updateById(user);
        return ResultUtil.success(200, "重置成功");
    }

    @Override
    public Result orgStop(String flag, Integer id) {
        COrg org = orgMapper.selectById(id);
        if (Utils.isNotNull(org)) {
            if ("1".equals(flag)) {
                org.setStatus("2");
            } else if ("2".equals(flag)) {
                org.setStatus("1");
            }
        }
        orgMapper.updateById(org);
        //停用机构账号
        SysUser sysUser = sysUserMapper.selectOne(new QueryWrapper<SysUser>()
                .eq("relative_id", id)
                .eq("user_type", 1));
        if (Utils.isNotNull(sysUser)) {
            if ("1".equals(flag)) {
                sysUser.setStatus("2");
            } else if ("2".equals(flag)) {
                sysUser.setStatus("1");
            }
        }
        sysUserMapper.updateById(sysUser);
        return ResultUtil.success(200, "操作成功");
    }

    @Override
    public String getorgUser(String id) {
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("relative_id", id).eq("user_type", 1).eq("status", 1);
        SysUser user = sysUserMapper.selectOne(queryWrapper);
        if (Utils.isNotNull(user)) {
            return user.getUserId();
        }
        return null;
    }

    /**
     * 校验账号是否存在
     */
    public boolean checkUserIdIsExist(String userId) {
        Integer count = sysUserMapper.selectCount(new QueryWrapper<SysUser>().eq("user_id", userId));
        if (count > 0) {
            return true;
        }
        return false;
    }


    @Override
    public Map<String, Object> getOptionalDept() {
        Map<String, Object> map = new HashMap<>();
        List<COrg> cOrgs = orgMapper.selectList(new QueryWrapper<COrg>().eq("status", 1));
        map.put("orgName", cOrgs);
        return map;
    }

    @Override
    public List<CDOrg> getSelectedOrg(String devId) {
        Map<String, Object> map = new HashMap<>();
        QueryWrapper<CDOrg> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 1).eq("device_id", devId);
        return cdOrgMapper.selectList(queryWrapper);
    }
}
